import React, { useState, useEffect } from 'react';
import { Table, Tag, Space, Button, Modal, Form, Input, Select, message } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined, MinusCircleOutlined, ExclamationCircleOutlined, DeleteOutlined } from '@ant-design/icons';
import api, { TravelItem } from '../../services/api';

// 生成随机图片链接的函数
// const generateRandomImageUrl = () => {
//   const randomNumber = Math.floor(Math.random() * 1000); // 生成 0 到 999 之间的随机数
//   return `https://picsum.photos/800/600?random=${randomNumber}`;
// };

// 模拟数据

interface AuditProps {
  userRole: string;
}

// 自定义滚动条样式
const scrollbarStyle = `
  /* 滚动条整体样式 */
  ::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }

  /* 滚动条轨道 */
  ::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }

  /* 滚动条滑块 */
  ::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 4px;
  }

  /* 滚动条滑块悬停时 */
  ::-webkit-scrollbar-thumb:hover {
    background: #555;
    border-radius: 4px;
  }
`;

// 创建 style 元素并插入到文档中
const styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.appendChild(document.createTextNode(scrollbarStyle));
document.head.appendChild(styleElement);

const AuditList: React.FC<AuditProps> = ({ userRole }) => {
  const [travels, setTravels] = useState<TravelItem[]>([]);
  const [filter, setFilter] = useState<string>('all');
  const [deletedFilter, setDeletedFilter] = useState<string>('false'); // 默认只显示未删除的游记
  const [rejectVisible, setRejectVisible] = useState<boolean>(false);
  const [currentTravel, setCurrentTravel] = useState<TravelItem | null>(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 获取游记列表数据
  const fetchTravels = async (page = 1, status = 'all', keyword = '', deleted = deletedFilter) => {
    setLoading(true);
    try {
      // 转换删除状态参数
      const isDeleted = deleted === 'true' ? true :
        deleted === 'false' ? false : undefined;

      // 如果有搜索关键词，使用搜索API
      let response;
      if (keyword) {
        response = await api.searchTravels(keyword, page, pagination.pageSize, isDeleted);
      } else {
        response = await api.getAllTravels(
          page,
          pagination.pageSize,
          status !== 'all' ? status : undefined,
          isDeleted
        );
      }

      // 格式化游记数据
      const formattedData = response.data.map(item => ({
        ...item,
        // 确保submitTime存在，如果不存在则使用createdAt
        submitTime: item.submitTime || new Date(item.createdAt).toLocaleString()
      }));

      setTravels(formattedData);
      setPagination({
        ...pagination,
        current: response.currentPage,
        total: response.total
      });
    } catch (error) {
      console.error('获取游记列表失败:', error);
      message.error('获取游记列表失败，请检查网络连接');

      // 如果API请求失败，使用本地数据（仅用于开发/演示阶段）
      const mockData = [
        {
          id: '1',
          title: '示例游记',
          content: '这是一篇示例游记内容...',
          images: ['https://picsum.photos/300/200?random=1'],
          status: 'pending',
          author: {
            _id: 'user1',
            nickname: '测试用户',
            avatar: 'https://randomuser.me/api/portraits/men/1.jpg'
          },
          isDeleted: false,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          submitTime: new Date().toLocaleString()
        }
      ];
      setTravels(mockData as TravelItem[]);
    } finally {
      setLoading(false);
    }
  };

  // 首次加载和筛选条件变化时获取数据
  useEffect(() => {
    fetchTravels(pagination.current, filter, searchText, deletedFilter);
  }, [filter, deletedFilter]);

  // 处理搜索
  const handleSearch = () => {
    fetchTravels(1, filter, searchText, deletedFilter);
  };

  // 处理分页变化
  const handleTableChange = (pagination: any) => {
    setPagination(pagination);
    fetchTravels(pagination.current, filter, searchText, deletedFilter);
  };

  // 审核通过
  const handleApprove = (id: string) => {
    Modal.confirm({
      title: '确认审核通过',
      icon: <ExclamationCircleOutlined />,
      content: '确定要通过这篇游记吗？通过后将对所有用户可见。',
      onOk: async () => {
        try {
          await api.approveTravel(id);
          message.success('游记已通过审核');
          // 刷新数据
          fetchTravels(pagination.current, filter, searchText, deletedFilter);
        } catch (error) {
          console.error('审核通过失败:', error);
          message.error('操作失败，请稍后重试');
        }
      },
    });
  };

  // 显示拒绝对话框
  const showRejectModal = (travel: TravelItem) => {
    setCurrentTravel(travel);
    setRejectVisible(true);
    form.resetFields();
  };

  // 拒绝游记
  const handleReject = () => {
    form.validateFields().then(async values => {
      if (currentTravel) {
        try {
          await api.rejectTravel(currentTravel.id, values.rejectReason);
          message.success('已拒绝该游记');
          setRejectVisible(false);
          // 刷新数据
          fetchTravels(pagination.current, filter, searchText, deletedFilter);
        } catch (error) {
          console.error('拒绝游记失败:', error);
          message.error('操作失败，请稍后重试');
        }
      }
    });
  };

  // 删除游记
  const handleDelete = (id: string) => {
    if (userRole === 'admin') {
      Modal.confirm({
        title: '确认删除',
        icon: <ExclamationCircleOutlined />,
        content: '确定要删除这篇游记吗？此操作不可恢复。',
        onOk: async () => {
          try {
            await api.deleteTravel(id);
            message.success('游记已删除');
            // 刷新数据
            fetchTravels(pagination.current, filter, searchText, deletedFilter);
          } catch (error) {
            console.error('删除游记失败:', error);
            message.error('操作失败，请稍后重试');
          }
        },
      });
    } else {
      Modal.warning({
        title: '无权限',
        content: '您没有删除游记的权限，请联系管理员。',
      });
    }
  };

  // 查看游记详情
  const viewDetail = (travel: TravelItem) => {
    Modal.info({
      title: travel.title,
      width: 800,
      icon: null,
      className: 'travel-detail-modal',
      content: (
        <div className="travel-detail-content">
          <div className="travel-info-section">
            <p><strong>作者：</strong>{travel.author.nickname}</p>
            <p><strong>提交时间：</strong>{travel.submitTime || new Date(travel.createdAt).toLocaleString()}</p>
            {travel.location && (
              <p><strong>位置：</strong>{travel.location}</p>
            )}
            <p><strong>状态：</strong>
              <Tag
                color={
                  travel.isDeleted ? 'gray' :
                    travel.status === 'approved' ? 'green' :
                      travel.status === 'rejected' ? 'red' :
                        travel.status === 'pending' ? 'gold' : 'default'
                }
              >
                {travel.isDeleted ? '已删除' :
                  travel.status === 'approved' ? '已通过' :
                    travel.status === 'rejected' ? '未通过' :
                      travel.status === 'pending' ? '待审核' : '未知'
                }
              </Tag>
            </p>
            {travel.status === 'rejected' && travel.rejectReason && (
              <p><strong>拒绝原因：</strong><span style={{ color: 'red' }}>{travel.rejectReason}</span></p>
            )}
          </div>

          <div className="travel-content-section">
            <p><strong>内容：</strong></p>
            <div className="travel-content-box">{travel.content}</div>
          </div>

          {/* 显示图片 */}
          {travel.images && travel.images.length > 0 && (
            <div className="travel-images-section">
              <p><strong>图片：</strong></p>
              <div className="travel-images-container">
                {travel.images.map((imageUrl: string, index: number) => (
                  <img
                    key={index}
                    src={imageUrl.startsWith('http') ? imageUrl : `http://localhost:5000${imageUrl}`}
                    alt={`图片 ${index + 1}`}
                    className="travel-image"
                  />
                ))}
              </div>
            </div>
          )}
          {/* 显示视频 */}
          {travel.video && (
            <div className="travel-video-section">
              <p><strong>视频：</strong></p>
              <video
                src={travel.video.startsWith('http') ? travel.video : `http://localhost:5000${travel.video}`}
                controls
                className="travel-video"
              />
            </div>
          )}
        </div>
      ),
    });
  };

  const columns = [
    {
      title: '游记ID',
      dataIndex: 'id',
      key: 'id',
      ellipsis: true,
      width: 100,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
      width: 150,
      render: (title: string) => (
        <span style={{ fontWeight: 500 }}>{title}</span>
      )
    },
    {
      title: '作者',
      key: 'author',
      ellipsis: true,
      width: 120,
      render: (_: any, record: TravelItem) => (
        <span>{record.author.nickname}</span>
      )
    },
    {
      title: '提交时间',
      key: 'submitTime',
      ellipsis: true,
      width: 120,
      render: (_: any, record: TravelItem) => (
        <span>{record.submitTime || new Date(record.createdAt).toLocaleString()}</span>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string, record: TravelItem) => {
        let color = '';
        let text = '';
        let icon = null;

        // 优先判断是否已删除
        if (record.isDeleted) {
          color = 'gray';
          text = '已删除';
          icon = <DeleteOutlined />;
        } else {
          switch (status) {
            case 'pending':
              color = 'gold';
              text = '待审核';
              break;
            case 'approved':
              color = 'green';
              text = '已通过';
              icon = <CheckCircleOutlined />;
              break;
            case 'rejected':
              color = 'red';
              text = '未通过';
              icon = <CloseCircleOutlined />;
              break;
            default:
              color = 'default';
              text = '未知';
          }
        }
        return (
          <Tag color={color} icon={icon}>
            {text}
          </Tag>
        );
      },
      width: 80,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: TravelItem) => (
        <Space size="middle">
          <Button type="link" onClick={() => viewDetail(record)}>查看</Button>

          {record.status === 'pending' && !record.isDeleted && (
            <>
              <Button type="link" style={{ color: 'green' }} onClick={() => handleApprove(record.id)}>通过</Button>
              <Button type="link" danger onClick={() => showRejectModal(record)}>拒绝</Button>
            </>
          )}

          {!record.isDeleted && (
            <Button type="link" style={{ color: 'gray' }} onClick={() => handleDelete(record.id)}>删除</Button>
          )}
        </Space>
      ),
      width: 250,
    },
  ];

  return (
    <div style={{ padding: '0 10px' }}>
      <h2 style={{ margin: '24px 0', fontSize: '20px', fontWeight: 'bold' }}>游记审核管理</h2>

      <div style={{ marginBottom: 20, background: '#f5f5f5', padding: '15px', borderRadius: '8px' }}>
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          <Space>
            <Input
              placeholder="根据游记内容搜索"
              value={searchText}
              onChange={(e) => {
                setSearchText(e.target.value);
                // 当输入框被清空时，触发搜索
                if (!e.target.value) {
                  fetchTravels(1, filter, '', deletedFilter);
                }
              }}
              style={{ width: 300 }}
              onPressEnter={handleSearch}
              allowClear
            />
            <Button type="primary" onClick={handleSearch}>搜索</Button>
          </Space>

          <Space size="large">
            <Space.Compact>
              <span style={{ marginRight: 8, fontWeight: 500 }}>状态筛选：</span>
              <Select
                value={filter}
                onChange={setFilter}
                style={{ width: 150 }}
                options={[
                  { value: 'all', label: '全部' },
                  { value: 'pending', label: '待审核' },
                  { value: 'approved', label: '已通过' },
                  { value: 'rejected', label: '未通过' },
                ]}
              />
            </Space.Compact>

            <Space.Compact>
              <span style={{ marginRight: 8, fontWeight: 500 }}>删除状态：</span>
              <Select
                value={deletedFilter}
                onChange={setDeletedFilter}
                style={{ width: 150 }}
                options={[
                  { value: 'false', label: '未删除' },
                  { value: 'true', label: '已删除' },
                  { value: 'all', label: '全部' },
                ]}
              />
            </Space.Compact>
          </Space>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={travels}
        rowKey="id"
        pagination={pagination}
        loading={loading}
        onChange={handleTableChange}
        rowClassName={(record) => record.isDeleted ? 'deleted-row' : ''}
        bordered
      />

      <style dangerouslySetInnerHTML={{
        __html: `
          .deleted-row {
            opacity: 0.65;
            background-color: #f5f5f5;
          }
          .ant-table-thead > tr > th {
            background-color: #f0f2f5;
            font-weight: bold;
          }
          
          /* 游记详情样式 */
          .travel-detail-content {
            max-height: 70vh;
            overflow-y: auto;
            padding-right: 10px;
          }
          
          .travel-info-section {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f0f0f0;
          }
          
          .travel-content-section {
            margin-bottom: 20px;
          }
          
          .travel-content-box {
            max-height: 200px;
            overflow-y: auto;
            padding: 10px;
            border: 1px solid #f0f0f0;
            border-radius: 4px;
            background-color: #fafafa;
          }
          
          .travel-images-section {
            margin-bottom: 20px;
          }
          
          .travel-images-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            max-height: 300px;
            overflow-y: auto;
          }
          
          .travel-image {
            max-width: 200px;
            max-height: 200px;
            object-fit: cover;
            border-radius: 4px;
            border: 1px solid #f0f0f0;
          }
          
          .travel-video-section {
            margin-bottom: 20px;
          }
          
          .travel-video {
            max-width: 100%;
            border-radius: 4px;
          }
        `
      }} />

      <Modal
        title="拒绝原因"
        open={rejectVisible}
        onOk={handleReject}
        onCancel={() => setRejectVisible(false)}
      >
        <Form form={form}>
          <Form.Item
            name="rejectReason"
            label="拒绝原因"
            rules={[{ required: true, message: '请输入拒绝原因' }]}
          >
            <Input.TextArea rows={4} placeholder="请输入拒绝原因" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AuditList;